package com.xiaoshuidi.cloud.module.member.xxljob;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.member.controller.app.activities.vo.MemberActivitiesValidCodeEnroll;
import com.xiaoshuidi.cloud.module.member.mq.producer.MemberVerifyCodeProducer;
import com.xiaoshuidi.cloud.module.member.pojo.activities.MemberActivities;
import com.xiaoshuidi.cloud.module.member.pojo.activities.MemberActivitiesEnroll;
import com.xiaoshuidi.cloud.module.member.repository.MemberActivitiesEnrollRepository;
import com.xiaoshuidi.cloud.module.member.repository.MemberActivitiesRepository;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class MemberVerifyCodeJob {
    private final MemberActivitiesRepository memberActivitiesRepository;
    private final MemberActivitiesEnrollRepository memberActivitiesEnrollRepository;

    private final MemberVerifyCodeProducer producer;


    @TenantIgnore
    @XxlJob("member-scanner-expired-code-job")
    @Transactional
    public void execute() {
        long start = new Date().getTime();
        log.info("member改变二维码状态定时任务开始" + start);
        //扫描活动报名表中还有10分钟就要活动结束的活动
        LocalDateTime now = LocalDateTime.now();
        //找出待核销中活动结束时间距离当前时间小于等于10分钟的
        LocalDateTime offset = LocalDateTimeUtil.offset(now, 10, ChronoUnit.MINUTES);
        List<MemberActivities> list = memberActivitiesRepository.selectTobeValidList(offset);
        //这些活动还有多少报名的待核销的码
        if (list != null && list.size() > 0) {
            List<Long> ids = list.stream().map(MemberActivities::getId).collect(Collectors.toList());
            List<MemberActivitiesValidCodeEnroll> enrolls = memberActivitiesEnrollRepository.getUnverified(ids);
            for (MemberActivitiesValidCodeEnroll enroll : enrolls) {
                producer.sendVerifyCodeMessage(enroll.getId(), enroll.getEndTime());
            }
        }
        long end = new Date().getTime();
        log.info("member改变二维码状态定时任务结束" + new Date().getTime() + "历时：" + (end - start));
    }
}
